import 'package:flutter/material.dart';
import './link_url.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:projectone/bean/books_bean.dart';
import 'package:projectone/network_get_data.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'book_detail_pages.dart';

///搜索页面
class SearchPage extends StatefulWidget{
  @override
  _SearchState createState() {
    // TODO: implement createState
    return _SearchState();
  }

}
class _SearchState extends State<SearchPage>{
  final _controller=TextEditingController();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _initSharedPreferences();
  }
  List<String> historyList=new List();
  _initSharedPreferences() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    List<String> history=prefs.getStringList('search_history');
    if(history!=null){
        setState(() {
          historyList=history;
        });
    }
  }
  _saveHistory(String inputText) async{
    //print(historyList.indexOf(inputText));
    if(historyList.indexOf(inputText)==-1) historyList.add(inputText);
    else {
      int index=historyList.indexOf(inputText);
      if(index!=historyList.length-1) {
        historyList.add(historyList[index]);
        historyList.removeAt(index);
      }
    }
    if(historyList.length>10) historyList.removeAt(0);
    //historyList.forEach((element) {print(element);});
    SharedPreferences prefs = await SharedPreferences.getInstance();
    //String saveJson=json.encode(historyList);
    prefs.setStringList('search_history', historyList);
  }
  _changeHistory(int index) async{
    if(index!=historyList.length-1) {
      historyList.add(historyList[index]);
      historyList.removeAt(index);
      SharedPreferences prefs = await SharedPreferences.getInstance();
      //String saveJson=json.encode(historyList);
      prefs.setStringList('search_history', historyList);
      setState(() {

      });
    }
  }
  _deleteHistory(int index) async{
    historyList.removeAt(index);
    SharedPreferences prefs = await SharedPreferences.getInstance();
    //String saveJson=json.encode(historyList);
    prefs.setStringList('search_history', historyList);
    setState(() {

    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Scaffold(
      appBar: AppBar(
        title: new TextField(
          controller: _controller,
          textAlign: TextAlign.center,
          maxLines: 1,
          style: TextStyle(color: Colors.white),
          decoration: new InputDecoration(
            hintText: '输入你想搜索的内容',
            hintStyle: TextStyle(color: Colors.grey),
          ),
        ),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.search),
            onPressed: (){
              if(_controller.text.length==0)
              EasyLoading.showInfo('未输入内容');
              else{
                _saveHistory(_controller.text.trim());
                Navigator.push(context, MaterialPageRoute(builder: (context){
                  return SearchListPage(_controller.text.trim());
                }));
              }
          },)
        ],
      ),
      body: new ListView.builder(
          itemCount: historyList.length+1,
          itemBuilder: ((BuildContext context,int i){
            return i==0?
                Text('搜索历史🕙',textAlign: TextAlign.center,style: TextStyle(fontWeight: FontWeight.bold))//第一项目
                :ListTile(title: Text(historyList[historyList.length-i],textAlign: TextAlign.start,style: TextStyle(fontWeight: FontWeight.bold)),
                trailing: IconButton(icon: Icon(Icons.cancel),
                  onPressed: (){
                    //删除按钮
                    _deleteHistory(historyList.length-i);
                  },
                ),
                onTap: (){
                  //整行点击事件
                  _changeHistory(historyList.length-i);
                  Navigator.push(context, MaterialPageRoute(builder: (context){
                    return SearchListPage(historyList[historyList.length-1]);
                  }));
                },
            );
          })),
    );
  }

}

class SearchListPage extends StatefulWidget{
  final String keyWords;

  @override
  _SearchListState createState() {
    // TODO: implement createState
    return _SearchListState(this.keyWords);
  }
  SearchListPage(this.keyWords);

}
class _SearchListState extends State<SearchListPage>{
  final String keyWords;
  _SearchListState(this.keyWords);

  List<BooksBean> mList=new List();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      EasyLoading.show(status: 'loading...');
    });
    NetworkData().getBookList(urlApi.searchBook,keyWords).then((value) =>
        setState(() {
          mList=value;
          EasyLoading.dismiss();
        })
    );

  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Scaffold(
      appBar: AppBar(
        title: Text('搜索结果'),
        centerTitle: true,
      ),
      body: new ListView.builder(
          itemCount: mList.length,
          itemBuilder: (BuildContext context,int i){
            BooksBean temp=mList[i];
            return new GestureDetector(
              child: Row(
                children: <Widget>[
                  new Container(
                      padding: EdgeInsets.all(4),
                      child: new Image(
                          height: 120,
                          width: 90,
                          image: NetworkImage(temp.bookCover))),
                  new Expanded(
                    child: Container(
                      color: i%2==1?Colors.limeAccent:Colors.white,
                      child: new Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          new Text('《'+temp.bookName+'》'),
                          new Text(temp.author),
                          new Divider(color: Colors.grey,height: 1,),
                          new Text(temp.type,maxLines: 2,overflow: TextOverflow.ellipsis,),
                          new Divider(color: Colors.grey,height: 1,),
                          new Text('最新章节:'+temp.lastTitle)
                        ],
                      ),
                    ),
                  )
                ],
              ),
              onTap: (){
                Navigator.push(context, MaterialPageRoute(builder: (context){
                  return BookInfoPage(temp.bookUrl,temp.bookName);
                }));
              },
            );
          }),
    );
  }

}